/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var DataSource = new Class({
    
    items        : new Array(),
    revision     : 0,
    pointer      : 0,
    slidingDoors : null,  
    
    Implements: [Options,Events],
    
    options: {
        id      : '',
        content : ''
    },
    
    initialize: function(options){
        this.setOptions(options);
    },
    
    addItem: function(item){        
        this.items[this.items.length] = item;
    },

    getId: function(){
        return this.options.id;
    },
    
    getCurrentItem: function(){
        return this.items[this.pointer];
    },
    
    getNextItem: function(){
        return this.items[(this.pointer+1)%this.items.length];
    },
    
    setSlidingDoors: function(sd){
        this.slidingDoors = sd;
    },
    
    shift: function(){
      this.pointer = ++this.pointer%this.items.length;  
    },
    
    updateRevision: function(){
        this.revision++;
    },
    
    startLoop: function(el){
        this.pointer = 0;        
        var loop = function(item){
            item.removeEvents();
            //kontrolni revize
            item.setRevision(this.revision);
            item.addEvent('end',function(item,revision){
                item.removeEvents('end');
                //kontrola dojezdu z predchoziho pruchodu
                console.log('source revision:'+this.revision+',item revision:'+revision);
                console.log('item end:'+item.options.url+' from el:'+item.options.el.getParent().getParent().get('id'));
                if(this.revision != revision){
                    console.error('Wrong revision');
                    return;
                }    
                //
                this.shift();
                if(this.pointer == 0){
                    console.log('Source timelineend. Trigger:'+item.options.url);
                    this.fireEvent('timelineEnd',this);
                }else{
                    loop(this.getCurrentItem());
                }                
            }.bind(this));
            item.show();
            this.slidingDoors.addEvent('end', function(slidingDoors){ 
                //slidingDoors.removeEvents('end');
                this.slidingDoors.removeEvents();
                //console.log()
                if(this.getNextItem() != item && ((this.pointer+1)%this.items.length) != 0){ 
                    //console.log('preloading item after:');
                    this.getNextItem().load(this.slidingDoors.getCurrent());
                }
            }.bind(this));
            this.slidingDoors.slide();      
        }.bind(this);
        
        this.items[this.pointer].load(this.slidingDoors.getCurrent()); 
        loop(this.items[this.pointer]);        
    },
    
    stopLoop: function(){
 
    }
    
});


